package com.iqiyi.pps.epg.core.service.broadcast;

import com.alibaba.fastjson.JSON;
import com.iqiyi.pps.epg.core.dao.control.LocationControlDao;
import com.iqiyi.pps.epg.core.dao.control.PlatformControlDao;
import com.iqiyi.pps.epg.core.dao.control.ProgramPlatformControlDao;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.model.channel.ChannelConfig;
import com.iqiyi.pps.epg.core.model.control.LocationControl;
import com.iqiyi.pps.epg.core.model.control.PlatformControl;
import com.iqiyi.pps.epg.core.model.control.ProgramPlatformControl;
import com.iqiyi.pps.epg.core.model.control.ProgramPlatformControlInfo;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.model.reservation.ReserveControl;
import com.iqiyi.pps.epg.core.rpc.qipu.QipuService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.service.reservation.ReservationService;
import org.apache.commons.lang.StringUtils;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.IntegerType;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Transactional
public class BroadcastControlServiceImpl implements BroadcastControlService {
    private static final Logger logger = LoggerFactory.getLogger(BroadcastControlServiceImpl.class);

    @Autowired
    private PlatformControlDao platformControlDao;
    @Autowired
    private LocationControlDao locationControlDao;
    @Autowired
    private ProgramPlatformControlDao programPlatformControlDao;
    @Autowired
    private QipuService qipuService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private ProgramService programService;
    @Autowired
    private ReservationService reservationService;

    private long lastUpdateCache = 0;
    private long refreshGap = 3000L;
    private Map<Long, List<PlatformControl>> channelCache = new ConcurrentHashMap<>(512);

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PlatformControl getPlatformByUnique(long fatherId, int platform) {
        Criteria criteria = platformControlDao.createCriteria();
        criteria.add(Restrictions.eq("fatherId", fatherId));
        criteria.add(Restrictions.eq("playPlatform", platform));
        return platformControlDao.findUnique(criteria);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public LocationControl getLocationByUnique(long fatherId, int location) {
        Criteria criteria = locationControlDao.createCriteria();
        criteria.add(Restrictions.eq("fatherId", fatherId));
        criteria.add(Restrictions.eq("location", location));
        return locationControlDao.findUnique(criteria);
    }

    @Override
    public boolean savePlatform(PlatformControl entity) {
        try {
            platformControlDao.save(entity);
            channelService.hasBroadcast(entity.getFatherId());
        } catch (Exception e) {
            logger.error("savePlatform fail ", e);
            return false;
        }
        return true;
    }

    @Override
    public boolean saveLocation(LocationControl entity) {
        try {
            locationControlDao.save(entity);
        } catch (Exception e) {
            logger.error("saveLocation fail ", e);
            return false;
        }
        return true;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<PlatformControl> getPlatformControls(long channelId) {
        return platformControlDao.findBy("fatherId", channelId);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<LocationControl> getLocationControls(long channelId) {
        return locationControlDao.findBy("fatherId", channelId);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public boolean isSetBroadcastControl(long channelId) {
        // Criteria criteria = platformControlDao.createCriteria();
        // criteria.add(Restrictions.eq("fatherId", channelId));
        // return platformControlDao.countCriteriaResult(criteria) > 0 ? true : false;
        String sql = "select count(*) from platform_control where father_id = :fatherId limit 1";
        SQLQuery query = platformControlDao.getSession().createSQLQuery(sql);
        Object obj = query.setParameter("fatherId", channelId).uniqueResult();
        return Long.valueOf(obj.toString()) > 0 ? true : false;
    }

    @Override
    public boolean sets(long channelId, List<PlatformControl> platformControls) {
        if (platformControls.size() < 1) {
            return false;
        }
        // 获取频道信息用于写奇谱
        ChannelBase channelBase = channelService.getChannelBase(channelId);
        if (channelBase == null) {
            return false;
        }

        // 判断是否台湾轮播台
        String newBlacklist = null;
        Boolean isLB = false;
        Boolean isTW = false;
        if (channelBase.getLiveType() == ChannelBase.LIVE_TYPE_LB) {
            isLB = true;
            // 11 为台湾台
            if(channelBase.getType() == 11) {
                isTW = true;
                newBlacklist = PlatformControl.TW_BLACKLIST;
            }else{
                newBlacklist = PlatformControl.NOT_TW_BLACKLIST;
            }
        }

        clearCache(channelId);
        try {
            for (PlatformControl item : platformControls) {
                Criteria criteria = platformControlDao.createCriteria();
                criteria.add(Restrictions.eq("fatherId", item.getFatherId()));
                criteria.add(Restrictions.eq("playPlatform", item.getPlayPlatform()));
                PlatformControl model = platformControlDao.findUnique(criteria);
                if (model != null) {
                    item.setId(model.getId());
                    platformControlDao.clear(model);
                }

                if(isLB) {
                    if(StringUtils.isBlank(item.getBlacklist())) {
                        item.setBlacklist(newBlacklist);
                    }else{
                       if(!isTW && !item.getBlacklist().contains("台湾")) {
                           item.setBlacklist(newBlacklist);
                       }else if(isTW) {
                           item.setBlacklist(newBlacklist);
                       }
                    }
                }

                platformControlDao.save(item);
            }
            channelService.hasBroadcast(channelBase);
            return writeQipuBroadcast(channelBase);
        } catch (Exception e) {
            logger.error("sets fail ", e);
            return false;
        }
    }

    private void doCheckClearFeed(  ProgramData programData , ChannelBase channelBase,Map<Integer, ProgramPlatformControl> platformControls ){
        boolean setOffLine = false;
        for(ProgramPlatformControl temp : platformControls.values()){
            if(temp.getAvailableStatus() == 0){
                setOffLine =true;
                break;
            }
        }
        if( setOffLine && programData.getQipuId() > 0 && programData.getType() != 7 ){
            programService.doCheckClearFeedByQipuId( programData.getQipuId() );
        }
    }

    public boolean setsWithProgram(long programId, Map<Integer, ProgramPlatformControl> platformControls) {
        logger.info("setsWithProgram programId={} start ", programId);
        if (platformControls.size() < 1) {
            return false;
        }
        // 获取节目信息用于写奇谱
        try {
            Criteria criteria = programPlatformControlDao.createCriteria();
            criteria.add(Restrictions.eq("programId", programId));
            List<ProgramPlatformControl> setList = programPlatformControlDao.find(criteria);
            ProgramPlatformControl temp = null;
            // List<ProgramPlatformControl> saveList = new ArrayList<ProgramPlatformControl>();
            ProgramData programData = programService.findProgramDataById(programId);
            ChannelBase channelBase = channelService.getChannelBase(programData.getFatherId());
            doCheckClearFeed(programData,channelBase, platformControls);
            // 判断是否台湾轮播台
            String newBlacklist = null;
            Boolean isLB = false;
            Boolean isTW = false;
            if (channelBase.getLiveType() == ChannelBase.LIVE_TYPE_LB) {
                isLB = true;
                // 11 为台湾台
                if(channelBase.getType() == 11) {
                    isTW = true;
                    newBlacklist = PlatformControl.TW_BLACKLIST;
                }else{
                    newBlacklist = PlatformControl.NOT_TW_BLACKLIST;
                }
            }


            if (setList.size() > 0) {
                for (ProgramPlatformControl oldSetting : setList) {
                    if (platformControls.containsKey(oldSetting.getPlayPlatform())) {
                        temp = platformControls.get(oldSetting.getPlayPlatform());
                        copyNewToOld(oldSetting, temp);
                    }
                    platformControls.put(oldSetting.getPlayPlatform(), oldSetting);
                }
            } else {
                List<PlatformControl> list = getPlatformControls(programData.getFatherId());
                for (PlatformControl oldSetting : list) {
                    if (!platformControls.containsKey(oldSetting.getPlayPlatform())) {
                        temp = new ProgramPlatformControl();
                        temp.setProgramId(programId);
                        copySetting(oldSetting, temp);
                        platformControls.put(temp.getPlayPlatform(), temp);
                    }
                }
            }
            for (ProgramPlatformControl saveTmp : platformControls.values()) {

                if(isLB) {
                    if(StringUtils.isBlank(saveTmp.getBlacklist())) {
                        saveTmp.setBlacklist(newBlacklist);
                    }else{
                        if(!isTW && !saveTmp.getBlacklist().contains("台湾")) {
                            saveTmp.setBlacklist(newBlacklist);
                        }else if(isTW) {
                            saveTmp.setBlacklist(newBlacklist);
                        }
                    }
                }

                programPlatformControlDao.save(saveTmp);
            }
            //   saveList.addAll(platformControls.values());
            // batchUpdateProgramPlatformControl(saveList);
            return writeQipuBroadcast(programData);
        } catch (Exception e) {
            logger.error("setsWithProgram fail ", e);
            return false;
        }

    }

    // @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public boolean setsbak(long channelId, List<PlatformControl> platformControls) {
        if (platformControls.size() < 1) {
            return false;
        }

        // 获取频道信息用于写奇谱
        ChannelBase channelBase = channelService.getChannelBase(channelId);
        if (channelBase == null) {
            return false;
        }

        Session session = platformControlDao.getSessionFactory().openSession();
        session.setFlushMode(FlushMode.COMMIT);
        Transaction transaction = session.beginTransaction();
        try {
            for (PlatformControl item : platformControls) {
                Criteria criteria = platformControlDao.createCriteria();
                criteria.add(Restrictions.eq("fatherId", item.getFatherId()));
                criteria.add(Restrictions.eq("playPlatform", item.getPlayPlatform()));
                PlatformControl model = platformControlDao.findUnique(criteria);
                if (model != null) {
                    item.setId(model.getId());
                    session.evict(model);
                }
                session.saveOrUpdate(item);
            }
            transaction.commit();
            transaction = null;
            session.flush();
            session.clear();
            channelService.hasBroadcast(channelBase);

            return writeQipuBroadcast(channelBase);
        } catch (Exception e) {
            logger.error("setsbak", e);
            transaction.rollback();
            return false;
        } finally {
            session.close();
        }
    }

    /**
     * 写节目播控
     *
     * @param programData
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public boolean writeQipuBroadcast(ProgramData programData) {
        logger.info("[writeQipuBroadcast] start programId={}", programData.getId());
        try {
            List<ProgramPlatformControl> platformControls = programPlatformControlDao.findBy("programId", programData.getId());
            if (platformControls.isEmpty()) {
                List<PlatformControl> list = findChannelCache(programData.getFatherId());
                if (!list.isEmpty()) {
                    ProgramPlatformControl temp = null;
                    for (PlatformControl channelControl : list) {
                        temp = new ProgramPlatformControl();
                        temp.setProgramId(programData.getId());
                        copySetting(channelControl, temp);
                        platformControls.add(temp);
                        programPlatformControlDao.save(temp);
                    }
                    //batchUpdateProgramPlatformControl(platformControls);
                }
            }
            boolean flag = writeEpisodeNewQipu(programData.getQipuId(),(programData.getTest() == 1|| programData.getType() == 7), platformControls);
            logger.info("[writeQipuBroadcast] end programId={}", programData.getId());
            return flag;
        } catch (Exception e) {
            logger.error("[writeQipuBroadcast][programId=" + programData.getId(), e);
            return false;
        }
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void fillProgramBroadcast( ProgramData programData ){
        List<ProgramPlatformControl> platformControls = programPlatformControlDao.findBy("programId", programData.getId());
        if (platformControls.isEmpty()) {
            List<PlatformControl> list = findChannelCache(programData.getFatherId());
            if (!list.isEmpty()) {
                ProgramPlatformControl temp = null;
                for (PlatformControl channelControl : list) {
                    temp = new ProgramPlatformControl();
                    temp.setProgramId(programData.getId());
                    copySetting(channelControl, temp);
                    platformControls.add(temp);
                    programPlatformControlDao.save(temp);
                }
            }
        }
    }

    private void copyNewToOld(ProgramPlatformControl oldPlatform, ProgramPlatformControl newControl) {
        oldPlatform.setIsCooperationAllowed(newControl.getIsCooperationAllowed());
        oldPlatform.setAvailableStatus(newControl.getAvailableStatus());
        oldPlatform.setIsDrm(newControl.getIsDrm());
        oldPlatform.setIpSegmentDelayTime(newControl.getIpSegmentDelayTime());
        oldPlatform.setBlacklist(newControl.getBlacklist());
        oldPlatform.setIsShareAllowed(newControl.getIsShareAllowed());
        oldPlatform.setLiveDelayTime(0);
        oldPlatform.setPlayPlatform(newControl.getPlayPlatform());
        oldPlatform.setRejectTop(newControl.getRejectTop());
        oldPlatform.setRejectSearch(newControl.getRejectSearch());
        oldPlatform.setRegionRejectSearch(newControl.getRegionRejectSearch());
        oldPlatform.setIsDownloadAllowed(newControl.getIsDownloadAllowed());
        oldPlatform.setRejectRecommend(newControl.getRejectRecommend());
    }

    private void copySetting(PlatformControl channelControl, ProgramPlatformControl programPlatformControl) {
        programPlatformControl.setAddTime(new Timestamp(System.currentTimeMillis()));
        programPlatformControl.setIsCooperationAllowed(channelControl.getIsCooperationAllowed());
        programPlatformControl.setAvailableStatus(channelControl.getAvailableStatus());
        programPlatformControl.setIsDrm(channelControl.getIsDrm().intValue());
        programPlatformControl.setIpSegmentDelayTime(channelControl.getIpSegmentDelayTime());
        programPlatformControl.setBlacklist(channelControl.getBlacklist());
        programPlatformControl.setIsShareAllowed(channelControl.getIsShareAllowed().intValue());
        programPlatformControl.setLiveDelayTime(0);
        programPlatformControl.setPlayPlatform(channelControl.getPlayPlatform());
        programPlatformControl.setRejectTop(channelControl.getRejectTop());
        programPlatformControl.setRejectSearch(channelControl.getRejectSearch());
        programPlatformControl.setRegionRejectSearch(channelControl.getRegionRejectSearch());
        programPlatformControl.setIsDownloadAllowed(channelControl.getIsDownloadAllowed().intValue());
        programPlatformControl.setRejectRecommend(channelControl.getRejectRecommend());
    }


    /**
     * 写新老奇谱播控
     *
     * @param channelInfo
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public boolean writeQipuBroadcast(ChannelBase channelInfo) {
        try {
            List<PlatformControl> platformControls = getPlatformControls(channelInfo.getId());

            // 获取枚举表相关信息等用于写奇谱
            List<ChannelConfig> platformConfigs = channelService.getConfig(ChannelConfig.PLAY_PLATFORM);

            // 判断是否预约中
            List<ReserveControl> reservations = reservationService.getCurrentMinuteDataByChannelId(channelInfo.getId());
            List<PlatformControl> platformControlsForOldQipu = new ArrayList(platformControls);
            if (reservations.size() > 0) {
                Map<Integer, ReserveControl> reservationMap = new HashMap();
                for (ReserveControl item : reservations) {
                    reservationMap.put(item.getPlatform(), item);
                }
                // 老奇谱写全部并且包含预约中的
                Iterator<PlatformControl> iterator = platformControlsForOldQipu.iterator();
                while (iterator.hasNext()) {
                    PlatformControl item = iterator.next();
                    if (reservationMap.containsKey(item.getPlayPlatform())) {
                        platformControlDao.getSession().evict(item); // detached
                        ReserveControl temp = reservationMap.get(item.getPlayPlatform());
                        item.setLiveDelayTime(temp.getDelayTime());
                        if (temp.getOpsStatus() == ReserveControl.OPSSTATUS_ONLINE) {
                            item.setAvailableStatus(PlatformControl.AVAILABLE_STATUS_ALLOW);
                        } else {
                            item.setAvailableStatus(PlatformControl.AVAILABLE_STATUS_DENY);
                        }
                        item.setRejectSearch(temp.getRejectSearch());
                        item.setBlacklist(temp.getBlacklist());
                        item.setRegionRejectSearch(temp.getRegionRejectSearch());
                    }
                }
                // 新奇谱不写预约中的
                iterator = platformControls.iterator();
                while (iterator.hasNext()) {
                    PlatformControl item = iterator.next();
                    if (reservationMap.containsKey(item.getPlayPlatform())) {
                        iterator.remove();
                    }
                }
            }

            boolean flag = true;
            if (platformControls.size() > 0) {
                flag &= writeNewQipu(channelInfo, platformControls, platformConfigs);
            }
            return flag;
        } catch (Exception e) {
            logger.error("[BroadcastControlServiceImpl][writeQipuBroadcast][exception=]", e);
            return false;
        }
    }

    /**
     * 写新老奇谱不检测是否预约中，主要是预约计划任务中使用
     *
     * @param channelInfo
     * @param platformControls
     * @param platformConfigs
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public boolean writeQipuBroadcastIgnoreReservation(ChannelBase channelInfo, List<PlatformControl> platformControls, List<ChannelConfig> platformConfigs) {
        if (platformControls.size() < 1) {
            return true;
        }

        boolean flag = true;
        flag &= writeNewQipu(channelInfo, platformControls, platformConfigs);

        // 老奇谱写全部
//        List<PlatformControl> allPlatformControls = getPlatformControls(channelInfo.getId());
//        Map<Integer, PlatformControl> map = new HashMap();
//        for (PlatformControl item : platformControls) {
//            map.put(item.getPlayPlatform(), item);
//        }
//
//        Iterator<PlatformControl> iterator = allPlatformControls.iterator();
//        while (iterator.hasNext()) {
//            PlatformControl item = iterator.next();
//            if (map.containsKey(item.getPlayPlatform())) {
//                platformControlDao.getSession().evict(item); // detached
//                PlatformControl temp = map.get(item.getPlayPlatform());
//                item.setLiveDelayTime(temp.getLiveDelayTime());
//                item.setAvailableStatus(temp.getAvailableStatus());
//                item.setRejectSearch(temp.getRejectSearch());
//                item.setBlacklist(temp.getBlacklist());
//            }
//        }

     //   flag &= writeOldQipu(channelInfo, platformControls, false);
        logger.info("[BroadcastControlServiceImpl][writeQipuBroadcastIgnoreReservation][flag={}]", flag);
        return flag;
    }

    /**
     * 写新奇谱播控
     *
     * @param channelInfo
     * @param platformControls
     * @param platformConfigs
     * @return
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    private boolean writeNewQipu(ChannelBase channelInfo, List<PlatformControl> platformControls, List<ChannelConfig> platformConfigs) {
        logger.info("[BroadcastControlServiceImpl][writeNewQipu][platformControls={}]", JSON.toJSONString(platformControls));
        for (int i = 0; i < 3; i++) {
            if (qipuService.addAccessPlayControlToQipu(channelInfo.getQipuId(),false, platformControls)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 写新奇谱播控
     *
     * @param episodeQipuId
     * @param searchForbidden
     * @param platformControls
     * @return
     */

    @Override
    public boolean writeEpisodeNewQipu(long episodeQipuId, boolean searchForbidden,List<ProgramPlatformControl> platformControls) {
        logger.info("[BroadcastControlServiceImpl][writeNewQipu][platformControls={}][qipuId={}]", JSON.toJSONString(platformControls), episodeQipuId);
        if (episodeQipuId < 1) {
            return false;
        }
        for (int i = 0; i < 3; i++) {
            if (qipuService.addAccessPlayControlToQipu(episodeQipuId,searchForbidden, platformControls)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 写老奇谱播控
     *
     * @return
     */
//    @Transactional(propagation = Propagation.NOT_SUPPORTED)
//    private boolean writeOldQipu(ChannelBase channelInfo, List<PlatformControl> platformControls, boolean isAll) {
//        logger.info("[BroadcastControlServiceImpl][writeOldQipu][channelId={}][qipuId={}][platform size={}]",
//                channelInfo.getId(), channelInfo.getOldQipuId(), platformControls.size());
//        // 写老奇谱需要把所有的播控都写入一遍
//        if (!isAll) {
//            List<PlatformControl> allPlatforms = getPlatformControls(channelInfo.getId());
//            if (platformControls != null) {
//                platformControls.clear();
//            } else {
//                platformControls = new ArrayList<PlatformControl>();
//            }
//
//            // 预约处理
//            List<ReserveControl> reservations = reservationService.getCurrentMinuteDataByChannelId(channelInfo.getId());
//            if (reservations != null && reservations.size() > 0) {
//                Map<Integer, ReserveControl> reservationMap = new HashMap();
//                for (ReserveControl item : reservations) {
//                    reservationMap.put(item.getPlatform(), item);
//                }
//                // 老奇谱写全部并且包含预约中的
//                Iterator<PlatformControl> iterator = allPlatforms.iterator();
//                while (iterator.hasNext()) {
//                    PlatformControl item = iterator.next();
//                    if (reservationMap.containsKey(item.getPlayPlatform())) {
//                        platformControlDao.getSession().evict(item); // detached
//                        ReserveControl temp = reservationMap.get(item.getPlayPlatform());
//                        item.setLiveDelayTime(temp.getDelayTime());
//                        if (temp.getOpsStatus() == ReserveControl.OPSSTATUS_ONLINE) {
//                            item.setAvailableStatus(PlatformControl.AVAILABLE_STATUS_ALLOW);
//                        } else {
//                            item.setAvailableStatus(PlatformControl.AVAILABLE_STATUS_DENY);
//                        }
//                        item.setBlacklist(temp.getBlacklist());
//                        item.setRejectSearch(temp.getRejectSearch());
//                        item.setRegionRejectSearch(temp.getRegionRejectSearch());
//                        platformControls.add(0, item);
//                    } else {
//                        platformControls.add(item);
//                    }
//                }
//            } else {
//                logger.info("[BroadcastControlServiceImpl][writeOldQipu][platformControls][add all platforms]");
//                platformControls.addAll(allPlatforms);
//            }
//
////            Map<Integer, PlatformControl> platformMap = new HashMap();
////            for (PlatformControl item : platformControls) {
////                platformMap.put(item.getPlayPlatform(), item);
////            }
////
////            platformControls.clear();
////            for (PlatformControl item : allPlatforms) {
////                if (platformMap.containsKey(item.getPlayPlatform())) {
////                    PlatformControl platform = platformMap.get(item.getPlayPlatform());
////                    platformControls.add(platform);
////                    logger.info("[BroadcastControlServiceImpl][writeOldQipu][platformControls={}]", JSON.toJSONString(platform));
////                } else {
////                    platformControls.add(item);
////                    logger.info("[BroadcastControlServiceImpl][writeOldQipu][platformControls={}]", JSON.toJSONString(item));
////                }
////            }
////            for (PlatformControl platform : allPlatforms) {
////                platformControls.add(platform);
////            }
////            //插入预约播控
////            if (reservePlatformControls.size() > 0) {
////                platformControls.addAll(0, reservePlatformControls);
////            }
//        }
//
//        logger.info("[BroadcastControlServiceImpl][writeOldQipu][platformControls size={}]", platformControls.size());
//
//        for (int i = 0; i < 3; i++) {
//            if (qipuService.addTvLiveBaseToQipu(channelInfo, platformControls)) {
//                return true;
//            }
//        }
//        return false;
//    }

    private List<PlatformControl> findChannelCache(long channelId) {
        long current = System.currentTimeMillis();
        List<PlatformControl> list = new ArrayList<PlatformControl>();
        synchronized (channelCache) {
            if (current - lastUpdateCache > refreshGap) {
                lastUpdateCache = current;
                channelCache.clear();
            }
            if (!channelCache.containsKey(channelId)) {
                list = getPlatformControls(channelId);
                channelCache.put(channelId, list);
            } else {
                list = channelCache.get(channelId);
            }
        }
        return list;
    }

    private void clearCache(long channelId) {
        synchronized (channelCache) {
            channelCache.remove(channelId);
        }
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Map<Long, Integer> fetchPlatControls(int liveType) {
        Map<Long, Integer> map = new HashMap<Long, Integer>();
        StringBuffer sql = new StringBuffer();
        sql.append("select  control.father_id channelId, sum(control.available_status) onlineNum ");
        sql.append(" from platform_control control,channel_base channel  ");
        sql.append(" where channel.id = control.father_id  and channel.live_type = ? ");
        sql.append(" and channel.is_enable != -1 ");
        sql.append(" GROUP BY control.father_id");
        List<Object[]> result = platformControlDao.getSession().createSQLQuery(sql.toString())
                .addScalar("channelId", new LongType())
                .addScalar("onlineNum", new IntegerType())
                .setInteger((0), liveType).list();
        for (Object[] simple : result) {
            map.put((Long) simple[0], (Integer) simple[1]);
        }
        return map;
    }

    /**
     * 获取需要自动播控下线的相关节目信息
     *
     * @return 节目信息列表
     */


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<ProgramPlatformControlInfo> fetchProgramPlatControls() {
        List<ProgramPlatformControlInfo> result = new ArrayList<>();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT control.program_id programId, ");
        sql.append("program.chat_room_id chatroomId, program.chat_enable chatEnable, ");
        sql.append("channel.id channelId, channel.live_type liveType, program.program_name programName ");
        sql.append("FROM program_platform_control control, live_episode program ");
        sql.append("LEFT JOIN channel_base channel ON channel.id = program.father_id ");
        sql.append("WHERE program.id = control.program_id AND program.is_delete != 1 ");
        sql.append("AND program.start_play_time<  ADDDATE( now() , INTERVAL -channel.max_playback_period SECOND )  AND control.available_status = 1 ");
        sql.append("GROUP BY control.program_id ");

        List<Object[]> sqlResult = programPlatformControlDao.getSession().createSQLQuery(sql.toString())
                .addScalar("programId", new LongType())
                .addScalar("chatroomId", new LongType())
                .addScalar("chatEnable", new IntegerType())
                .addScalar("channelId", new LongType())
                .addScalar("liveType", new IntegerType())
                .addScalar("programName", new StringType())
                .list();

        for (Object[] simple : sqlResult) {
            ProgramPlatformControlInfo info = new ProgramPlatformControlInfo();
            info.setProgramId((Long) simple[0]);
            info.setChatroomId((Long) simple[1]);
            info.setChatEnable(((Integer) simple[2]) == 1);
            info.setChannelId((Long) simple[3]);
            info.setLiveType((Integer) simple[4]);
            info.setProgramName((String) simple[5]);
            result.add(info);
        }

        return result;

    }

    //@param gapTime 自动播控下线过期时长(s) 转换 00：00：00
    private static String transToTimeFormat(long gapTime) {
        long h = gapTime / 3600;
        long m = 0;
        long s = 0;
        gapTime = gapTime - 3600 * h;
        m = gapTime / 60;
        gapTime = gapTime - 60 * m;
        s = gapTime;
        return (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
    }

    @Override
    public List<ProgramPlatformControl> getProgramPlatformControls(long programId) {
        return programPlatformControlDao.findBy("programId", programId);
    }


//    public void batchUpdateProgramPlatformControl(List<ProgramPlatformControl> List) {
//        logger.info("batchUpdateProgramPlatformControl start");
//        Session session = programPlatformControlDao.getSessionFactory().openSession();
//        Transaction transaction = session.beginTransaction();
//        try {
//            for (ProgramPlatformControl tempData : List) {
//                session.saveOrUpdate(tempData);
//            }
//            transaction.commit();
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//            transaction.rollback();
//        } finally {
//            session.close();
//        }
//        logger.info("batchUpdateProgramPlatformControl end");
//    }

}
